package com.tinusgraglin.enclusiv.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.google.accompanist.placeholder.PlaceholderHighlight
import com.google.accompanist.placeholder.placeholder
import com.google.accompanist.placeholder.shimmer
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import com.tinusgraglin.enclusiv.EnclusivApp
import com.tinusgraglin.enclusiv.R
import com.tinusgraglin.enclusiv.datalayer.ShowedArticleProfile
import com.tinusgraglin.enclusiv.ui.theme.LoadingLightGrey

val articleStatsIcon = listOf(
    Pair(R.drawable.user, R.drawable.user),
    Pair(R.drawable.like, R.drawable.liked),
    Pair(R.drawable.love, R.drawable.loved)
)

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun ArticleCard(showedArticleProfile: ShowedArticleProfile?, onClick: () -> Unit) {
    val isLoading = showedArticleProfile == null

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
            .heightIn(min = 140.dp)
            .padding(2.dp)
            .placeholder(
                visible = isLoading,
                color = LoadingLightGrey,
                shape = RoundedCornerShape(10.dp),
                highlight = PlaceholderHighlight.shimmer(Color.White)
            ),
        elevation = if (isLoading) 0.dp else 2.dp,
        shape = RoundedCornerShape(10.dp),
        onClick = {
            if (!isLoading)
                onClick()
        }
    ) {
        if (showedArticleProfile != null) {
            val bottomIconLightState = listOf(
                false,
                showedArticleProfile.userArticleStats?.like ?: false,
                showedArticleProfile.userArticleStats?.collect ?: false
            )
            val firstImageUrl =
                if (showedArticleProfile.imageUrls.isEmpty()) null
                else showedArticleProfile.imageUrls[0]

            val articleStats = listOf(
                showedArticleProfile.articleStats.viewers,
                showedArticleProfile.articleStats.likes,
                showedArticleProfile.articleStats.collects,
            )

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 10.dp),
                horizontalAlignment = Alignment.Start
            ) {
                Spacer(Modifier.height(10.dp))
                Row(verticalAlignment = Alignment.CenterVertically) {
                    AsyncImage(
                        model = ImageRequest.Builder(LocalContext.current).apply {
                            data(showedArticleProfile!!.authorProfileImgUrl)
                            placeholder(R.drawable.user)
                        }.build(),
                        imageLoader = EnclusivApp.globalCoilImageLoader,
                        contentDescription = "Image: User Avatar",
                        modifier = Modifier
                            .size(16.dp)
                            .clip(CircleShape)
                    )

                    Spacer(Modifier.width(4.dp))
                    Text(
                        text = showedArticleProfile.authorName,
                        fontSize = 11.sp,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
                Spacer(Modifier.height(5.dp))
                Row {
                    Column(modifier = Modifier.fillMaxWidth(if (firstImageUrl != null) 0.7F else 1F)) {
                        Text(
                            text = showedArticleProfile.title,
                            fontWeight = FontWeight.Bold,
                            fontSize = 15.sp,
                            maxLines = 2,
                            overflow = TextOverflow.Ellipsis,
                        )
                        Spacer(Modifier.height(5.dp))
                        Text(
                            text = showedArticleProfile.contentCombined,
                            fontSize = 12.sp,
                            overflow = TextOverflow.Ellipsis,
                            maxLines = 6,
                            softWrap = true
                        )
                    }
                    if (firstImageUrl != null) {
                        Spacer(Modifier.width(14.dp))

                        AsyncImage(
                            model = ImageRequest.Builder(LocalContext.current).apply {
                                data(firstImageUrl)
                                placeholder(R.drawable.loading_black)
                            }.build(),
                            imageLoader = EnclusivApp.globalCoilImageLoader,
                            contentDescription = "Image: First Article Image",
                            modifier = Modifier
                                .aspectRatio(1.0F)
                                .padding(4.dp)
                                .fillMaxSize()
                        )
                    }
                }
                Spacer(Modifier.height(10.dp))
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.align(Alignment.End)
                ) {
                    articleStats.forEachIndexed { idx, stat ->
                        Spacer(Modifier.width(6.dp))
                        Icon(
                            painter = painterResource(
                                if (bottomIconLightState[idx]) articleStatsIcon[idx].second
                                else articleStatsIcon[idx].first
                            ),
                            contentDescription = "Icon: Viewers",
                            modifier = Modifier.size(14.dp)
                        )
                        Spacer(Modifier.width(4.dp))
                        Text(
                            text = stat.toString(),
                            fontSize = 10.sp
                        )
                    }
                }
                Spacer(Modifier.height(8.dp))
            }
        }
    }
}

@Composable
fun ArticleCardsList(
    showedArticleProfileList: List<ShowedArticleProfile?>,
    isRefreshing: Boolean = false,
    onRefresh: () -> Unit = {},
    itemOnClick: (Int, ShowedArticleProfile?) -> Unit
) {
    SwipeRefresh(state = rememberSwipeRefreshState(isRefreshing), onRefresh = onRefresh) {
        LazyColumn(modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Top) {
            itemsIndexed(showedArticleProfileList) { i, it ->
                ArticleCard(showedArticleProfile = it) {
                    itemOnClick(i, it)
                }
            }
        }
    }
}
